package com.soup.lab.basic.exec;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

public class RuntimeContext {

    private Map<String /* bizKey */, BizCounter> counterMap = new ConcurrentHashMap<>();

    private BizFetchPolicy policy;
    private DataFetcher dataFetcher;

    public RuntimeContext(BizFetchPolicy policy, DataFetcher dataFetcher) {
        this.policy = policy;
        this.dataFetcher = dataFetcher;
    }

    public void setPolicy(BizFetchPolicy policy) {
        this.policy = policy;
    }

    public void setDataFetcher(DataFetcher dataFetcher) {
        this.dataFetcher = dataFetcher;
    }

    private static class BizCounter {
        private AtomicLong total;
        private AtomicLong complete;

    }

    public boolean fetch() {
        return policy.fetch(dataFetcher);
    }

    private interface BizFetchPolicy {

        boolean fetch(DataFetcher fetcher);
    }

    public static class SimpleFetchPolicy implements BizFetchPolicy {

        @Override
        public boolean fetch(DataFetcher fetcher) {
            BizThread thread = (BizThread) Thread.currentThread();
            String bizKey = thread.getBizKey();
            List<String> ids = fetcher.fetchByKey(bizKey);
            if(ids == null || ids.isEmpty()) {
                return false;
            }
            thread.getQueue().addAll(ids.stream().map(i -> (Runnable)() -> System.out.println(i)).collect(Collectors.toList()));
            return true;
        }
    }

    public interface DataFetcher {

        Map<String, Integer> countByKey();

        List<String> fetchByKey(String bizKey);

    }


}
